#pragma once
#include <iostream>
using namespace std;

namespace gm
{
	template<class T>
	class vector
	{
	public:
		typedef T* iterator;
		typedef const T* const_iterator;

		vector()
		{}

		//vector(const vector<T>& v)
		//{
		//	_start = new T[v.capacity()];
		//	memcpy(_start,v._start,sizeof(T)*v.size());
		//	_finish = _start + v.size();
		//	_endofstorage = _start + v._endofstorage();
		//}

		vector(const vector<T>& v)
		{
			reverse(v.capacity());
			for (auto e : v)
			{
				this->push_back(e);
			}
		}

		void swap(vector<T>& v)
		{
			std::swap(_start,v._start);
			std::swap(_finish, v._finish);
			std::swap(_endofstorage, v._endofstorage);
		}

		vector<T>& operator = (vector<T> tmp)
		{
			swap(tmp);
			return *this;
		}

		~vector()
		{
			if (_start)
			{
				delete[] _start;
				_start = _finish = _endofstorage = nullptr;
			}
		}

		iterator start()
		{
			return _start;
		}
		iterator end()
		{
			return _finish;
		}

		const_iterator start() const
		{
			return _start;
		}
		const_iterator end() const
		{
			return _finish;
		}

		void reserve(size_t n)
		{
			if (n > size())
			{
				size_t old = size();
				T* tmp = new T[n];
				if (_start)
				{
					memcpy(tmp,_start,sizeof(T)*size());
					delete[] _start;
				}
				_start = tmp;
				_finish = _start + old;
				_endofstorage = _start + n;
			}
		}

		void resize(size_t n, T val = T())
		{
			if (n > size())
			{
				reserve(n);
				while (_finish < _start + n)
				{
					*_finish = val;
					++_finish;
				}
			}
			else
			{
				_finish = _start + n;
			}
		}

		void push_back(const T& x)
		{
			if (_finish == _endofstorage)
			{
				size_t newcapcity = capacity() == 0 ? 4 : capacity() * 2;
				reserve(newcapcity);
			}
			*_finish = x;
			_finish++;
		}

		void pop_back()
		{
			assert(size() > 0);
			--_finish;
		}

		void insert(iterator pos , const T& val)
		{
			assert(pos >= _start && pos <= _finish);

			if (_finish == _endofstorage)
			{
				size_t len = pos - _start;
				reserve(capacity() == 0 ? 4 : capacity() * 2);
				pos = _start + len;
			}

			momove(pos + 1, pos, sizeof(T)*(_finish - pos));
			*pos = val;
			_finish++;
		}

		void erase(iterator pos)
		{
			assert(pos >= _start);
			assert(pos < _finish);
			iterator it = pos + 1;
			while (it < _finish)
			{
				*(it - 1) = *it;
				++it;
			}
			_finish--;
			return pos;
		}

		int size()
		{
			return _finish - _start;
		}

		int capacity()
		{
			return _endofstorage - _start;
		}

		T& operator[](size_t pos)
		{
			assert(pos < size());
			return _start[pos];
		}
	private:
		iterator _start = nullptr;
		iterator _finish = nullptr;
		iterator _endofstorage = nullptr;
	};
}